﻿using System;
using System.Linq;
using API.IRepositories;
using API.EntityModels;
using API.Helpers;


namespace API.Repositories
{
    public class FoodOrderRepository : IFoodOrderRepository
    {
        public void Delete(int id)
        {
            var emptyEntity = new FoodOrder() { FoodOrderId = id };
            using (var entityConnection = ConnectionHelper.GetEntityConnection())
            {
                entityConnection.FoodOrders.Attach(emptyEntity);
                entityConnection.FoodOrders.DeleteObject(emptyEntity);
                entityConnection.SaveChanges();
            }
        }

        public IQueryable<FoodOrder> Get(int foodOrderId)
        {
            var entities = ConnectionHelper.GetEntityConnection();
            return from d in entities.FoodOrders
                   where d.FoodOrderId == foodOrderId
                   select d;
        }

        public EntityModels.FoodOrder Save(FoodOrder entity, Type baseEmptyEntityOnType)
        {
            using (var entityConnection = ConnectionHelper.GetEntityConnection())
            {
                if (entity.FoodOrderId > 0)
                {
                    var emptyEntity = EntityFrameworkHelper.BuildEmptyEntityForAttachment(entity, baseEmptyEntityOnType);
                    emptyEntity.FoodOrderId = entity.FoodOrderId;
                    entityConnection.FoodOrders.Attach(emptyEntity);
                    entityConnection.FoodOrders.ApplyCurrentValues(entity);
                }
                else
                {
                    entity = EntityFrameworkHelper.ResetEntityForAdd(entity, baseEmptyEntityOnType);
                    entity.Created = DateTime.Now;
                    entityConnection.FoodOrders.AddObject(entity);
                }

                entityConnection.SaveChanges();
                return Get().FirstOrDefault(d => d.FoodOrderId == entity.FoodOrderId);
            }
        }


        public IQueryable<FoodOrder> Get()
        {
            return ConnectionHelper.GetEntityConnection().FoodOrders.AsQueryable();
        }
    }
}




